package com.dongway.netcondition.service;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import com.dongway.core.common.ValidationException;
import com.dongway.core.service.BaseService;
import com.dongway.netcondition.model.User;

@Service
public class UserService extends BaseService {

    public User getUserByLogin(String login) {
        String sql = "select * from t_user where login=?";
        return getDao().queryForObject(User.class, sql, login);
    }


    public void login(User user) {
        User exits = getUserByLogin(user.getLogin());
        String pwd =
                DigestUtils
                    .md5DigestAsHex((StringUtils.trimToEmpty(user.getPassword()).getBytes()));
        if (null != exits && StringUtils.equals(pwd, exits.getPassword())) {
            Subject currentUser = SecurityUtils.getSubject();
            UsernamePasswordToken token = new UsernamePasswordToken(user.getLogin(), pwd);
            token.setRememberMe(false);
            currentUser.login(token);
            currentUser.getSession().setAttribute("user", exits);
        } else {
            throw new ValidationException("用户或密码错误!");
        }
    }


    public void register(User user) {
        if (StringUtils.isBlank(user.getLogin()) || StringUtils.isBlank(user.getPassword())) {
            throw new ValidationException("用户名,密码不能为空,请重新注册。");
        }
        User exits = getUserByLogin(user.getLogin());
        if (null != exits) {
            throw new ValidationException(user.getLogin() + "已存在,请重新注册。");
        }
        String pwd =
                DigestUtils
                    .md5DigestAsHex((StringUtils.trimToEmpty(user.getPassword()).getBytes()));
        user.setPassword(pwd);
        user.setRole("admin");
        getDao().save(user);
    }
}
